<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" style="margin-bottom: 8px;justify-content: end;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['drug:inventory:add']"
        >新增</el-button>
      </el-col>
      
    </el-row>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点单号" prop="inventoryOrder">
        <el-input
          v-model="queryParams.inventoryOrder"
          placeholder="请输入盘点单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeInventoryDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="制单人" prop="documentCreator">
        <el-input
          v-model="queryParams.documentCreator"
          placeholder="请输入制单人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

   

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="盘点单号" align="center" prop="inventoryOrder" />
      <el-table-column label="盘点日期" align="center" prop="inventoryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.inventoryDate, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="documentCreator" />
      <el-table-column label="盘点状态" align="center" prop="inventoryStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drug:inventory:edit']">查看</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['drug:inventory:remove']" v-if="scope.row.inventoryStatus == '正在盘点'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品盘点对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" v-if="form.inventoryStatus=='正在盘点'">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="sava"
          >保存</el-button>
        </el-col>
        <el-col :span="1.5" v-if="form.inventoryStatus=='正在盘点'">
          <el-button
            type="success"
            plain
            icon="Edit"

            @click="conpleae"
          >完成盘点</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"

            @click="cancel"
          >返回</el-button>
        </el-col>
       
      </el-row>
        <div class="order-info">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="info-item">
                <label>盘点单号：</label>
                <div >{{ form.inventoryOrder }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <label>盘点人：</label>
                <div >{{ form.documentCreator }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <label>创建日期：</label>
                <div >{{ form.inventoryDate }}</div>
              </div>
            </el-col>
          </el-row>
      </div>
      <el-table v-loading="loading" :data="rugInventoryIntermediateList" v-if="form.inventoryStatus=='盘点完成'" >
        <el-table-column label="序号" align="center" prop="id" />
        <!-- <el-table-column label="盘点单号" align="center" prop="inventoryOrder" /> -->
        <el-table-column label="药品编码" align="center" prop="drugCode" />
        <el-table-column label="药品名称" align="center" prop="dockerDrug.drugGenericName" />
        <el-table-column label="药品规格" align="center" prop="dockerDrug.drugSpecification" />
        <el-table-column label="生产厂家" align="center" prop="dockerDrug.drugManufacturer">
          <template #default="scope">
            <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.dockerDrug.drugManufacturer"/>
          </template>
        </el-table-column>
        <el-table-column label="当前库存数量" align="center" prop="currentInventoryQuantity" />
        <el-table-column label="盘点库存量" align="center" prop="inventoriedQuantity" >
      
        </el-table-column>
        <el-table-column label="盈亏" align="center">
          <template #default="scope">
            <span :style="{ 
              color: (scope.row.currentInventoryQuantity - scope.row.inventoriedQuantity) > 0 ? '#F56C6C' : '#67C23A',
              fontWeight: '500'
            }">
              {{ scope.row.currentInventoryQuantity - scope.row.inventoriedQuantity }}
            </span>
          </template>
        </el-table-column>        
        <el-table-column label="备注" align="center" prop="remarks">
         
        </el-table-column>
      </el-table>
      <el-table v-loading="loading" :data="rugInventoryIntermediateList" v-if="form.inventoryStatus=='正在盘点'" >
        <el-table-column label="序号" align="center" prop="id" />
        <!-- <el-table-column label="盘点单号" align="center" prop="inventoryOrder" /> -->
        <el-table-column label="药品编码" align="center" prop="drugCode" />
        <el-table-column label="药品名称" align="center" prop="dockerDrug.drugGenericName" />
        <el-table-column label="药品规格" align="center" prop="dockerDrug.drugSpecification" />
        <el-table-column label="生产厂家" align="center" prop="dockerDrug.drugManufacturer">
          <template #default="scope">
            <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.dockerDrug.drugManufacturer"/>
          </template>
        </el-table-column>
        <el-table-column label="当前库存数量" align="center" prop="currentInventoryQuantity" />
        <el-table-column label="盘点库存量" align="center" prop="inventoriedQuantity" >
          <template #default="scope">
            <el-input v-model="scope.row.inventoriedQuantity" />
          </template>
        </el-table-column>
        <el-table-column label="盈亏" align="center">
          <template #default="scope">
            <span :style="{ 
              color: (scope.row.currentInventoryQuantity - scope.row.inventoriedQuantity) > 0 ? '#F56C6C' : '#67C23A',
              fontWeight: '500'
            }">
              {{ scope.row.currentInventoryQuantity - scope.row.inventoriedQuantity }}
            </span>
          </template>
        </el-table-column>        
        <el-table-column label="备注" align="center" prop="remarks">
          <template #default="scope">
            <el-input v-model="scope.row.remarks" />
          </template>
        </el-table-column>
      </el-table>
     
    </el-dialog>
  </div>
</template>

<script setup name="Inventory">
import { listInventory, getInventory, delInventory, addInventory, updateInventory } from "@/api/drug/inventory";
import { listRugInventoryIntermediate, getRugInventoryIntermediate, delRugInventoryIntermediate, addRugInventoryIntermediate, updateRugInventoryIntermediate } from "@/api/drug/rugInventoryIntermediate";
const { proxy } = getCurrentInstance();
const { doctor_packaging_unit, doctor_drug_manufacturer, doctor_drug_form, sys_common_status, sys_yes_no, doctor_drug_category, doctor_invoice_item, doctor_drug_usage } = proxy.useDict('doctor_packaging_unit', 'doctor_drug_manufacturer', 'doctor_drug_form', 'sys_common_status', 'sys_yes_no', 'doctor_drug_category', 'doctor_invoice_item', 'doctor_drug_usage');


const inventoryList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeInventoryDate = ref([]);



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inventoryOrder: null,
    inventoryDate: null,
    documentCreator: null,
    inventoryStatus: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

const rugInventoryIntermediateList = ref([]);


/** 查询药品盘点列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeInventoryDate && '' != daterangeInventoryDate) {
    queryParams.value.params["beginInventoryDate"] = daterangeInventoryDate.value[0];
    queryParams.value.params["endInventoryDate"] = daterangeInventoryDate.value[1];
  }
  listInventory(queryParams.value).then(response => {
    inventoryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    inventoryOrder: null,
    inventoryDate: null,
    documentCreator: null,
    inventoryStatus: null
  };
  proxy.resetForm("inventoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeInventoryDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 获取当前用户信息
import useUserStore from '@/store/modules/user'
const user = useUserStore();
// 格式为 YYYY-MM-DD HH:MM:SS 的时间字符串
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// uuid随机数八位
function generate8DigitUUID() {
  const characters = '0123456789';
  let result = '';
  for (let i = 0; i < 12; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}
/** 新增按钮操作 */
function handleAdd() {
  // 判断，如果当前存在正在盘点，则不能添加
  if (inventoryList.value.some(item => item.inventoryStatus === '正在盘点')) {
    proxy.$modal.msgError("当前存在正在盘点的药品盘点单，无法添加新的盘点单");
    return;
  }
  reset();
  form.value.documentCreator = user.name;
  form.value.inventoryDate = formatDateTime(new Date());
  form.value.inventoryOrder = 'PD' + generate8DigitUUID();
  form.value.inventoryStatus = '正在盘点';
  console.log(form.value)
  addInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          getList();
        });
}

/** 查看按钮操作 */
function handleUpdate(row) {
  reset();
  listRugInventoryIntermediate({inventoryOrder:row.inventoryOrder}).then(response => {
    rugInventoryIntermediateList.value = response.rows;
    console.log(rugInventoryIntermediateList.value)
    // total.value = response.total;
    // loading.value = false;
  });
  form.value = row;
    open.value = true;
    title.value = "新增药品盘点";
}

function getList1() {
  loading.value = true;
  
}

// 完成盘点
function conpleae() {
  form.value.inventoryStatus = '盘点完成';
  updateInventory(form.value).then(response => {
    proxy.$modal.msgSuccess("盘点完成");
    rugInventoryIntermediateList.value.forEach(item => {
      updateRugInventoryIntermediate(item).then(response => {
      });
    });  
    getList();     
  });
}

/** 保存按钮 */
function sava() {
  rugInventoryIntermediateList.value.forEach(item => {
    updateRugInventoryIntermediate(item).then(response => {
      proxy.$modal.msgSuccess("保存成功");
    });
  });
  // proxy.$refs["inventoryRef"].validate(valid => {
  //   if (valid) {
  //     if (form.value.id != null) {
  //       updateInventory(form.value).then(response => {
  //         proxy.$modal.msgSuccess("修改成功");
  //         open.value = false;
  //         getList();
  //       });
  //     } else {
  //       addInventory(form.value).then(response => {
  //         proxy.$modal.msgSuccess("新增成功");
  //         open.value = false;
  //         getList();
  //       });
  //     }
  //   }
  // });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品盘点编号为"' + _ids + '"的数据项？').then(function() {
    return delInventory(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('drug/inventory/export', {
    ...queryParams.value
  }, `inventory_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style>
.order-info {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item label {
  width: 80px;
  color: #606266;
  flex-shrink: 0;
}

:deep(.el-input),
:deep(.el-select) {
  flex: 1;
}
</style>